package com.swgk.core.base.model.factory;

import android.text.TextUtils;

import com.swgk.core.helper.AppManagerHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.NetWorkUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * @author: 王彬臣
 * @date: 2021/7/26
 * @Description: PC token拦截器
 */
public class PCCookieInterceptor implements Interceptor {
    private static Map<String, String> commonParams;

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = rebuildRequest(chain.request());
        Response response = chain.proceed(request);
        // 输出返回结果
        try {
            Charset charset;
            charset = StandardCharsets.UTF_8;
            ResponseBody responseBody = response.peekBody(Long.MAX_VALUE);
            Reader jsonReader = new InputStreamReader(responseBody.byteStream(), charset);
            BufferedReader reader = new BufferedReader(jsonReader);
            StringBuilder sbJson = new StringBuilder();
            String line = reader.readLine();
            do {
                sbJson.append(line);
                line = reader.readLine();
            } while (line != null);
            MLog.d("api", "response: " + sbJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
            MLog.e(e.getMessage(), e.toString());
        }
        long timeDiff = response.receivedResponseAtMillis() - response.sentRequestAtMillis();
        String timeDiffStr = "";
        if (timeDiff >= 400) {
            timeDiffStr = "\n timeDiff:" + timeDiff + "ms";
        } else {
            timeDiffStr = " timeDiff:" + timeDiff + "ms";
        }

        MLog.d("apiTime", response.request().url().toString() + timeDiffStr);
        return response;
    }

    /**
     * 添加header
     */
    private Request rebuildRequest(Request request) throws IOException {
        Request newRequest;
        if ("POST".equals(request.method())) {
            newRequest = rebuildPostRequest(request);
        } else if ("GET".equals(request.method())) {
            newRequest = rebuildGetRequest(request);
        } else {
            newRequest = request;
        }
        String token = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.resourcePCToken, "");
//       String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJzdWIiOiIxMzMxNzk3MDIzMTkxNjAxMTUyIiwic2NvcGUiOiJkZWZhdWx0IiwiaXNzIjoiMTg0MDgyOTU4ODQiLCJsb2dpbiI6MTY0MTk4MDI2N30.jUEh1ZOyUj6Us_gkZdL4sLwDryivDoBJEyirS2ZYmt_pduHO0qK4Z1Ca3Xupks7-4ARaN08EahPQZ5wDAwxVE4ci8PDCe8FyM8EuQuYMAdb-ty7M4Inskh0kf13wqR4igFr5L0Zw_0c5Vm3uFcoT_-p9yD7SnNfdyuFhq4WroXc";
        if (TextUtils.isEmpty(token)) {
            token = "";
        } else {
            token = String.format("Bearer %s", token);
        }
        MLog.d("api", "request token  " + token);
        MLog.d("api", "request Url: 请求方式" + newRequest.method() + "  请求连接Url = " + newRequest.url().toString());
        // 可根据需求添加或修改header,
        if (!TextUtils.isEmpty(token)) {
            return newRequest.newBuilder()
                    .addHeader("Authorization", token)
                    .addHeader("platform", "android")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("type", "app-api-java")
                    .build();
        } else {
            return newRequest.newBuilder()
                    .addHeader("platform", "android")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("type", "app-api-java")
                    .build();
        }
    }

    /**
     * 可对post请求做特殊处理
     * 比如对某个接口做参数调整和参数替换，或添加公共请求参数
     */
    private Request rebuildPostRequest(Request request) {
        RequestBody originalRequestBody = request.body();
        try {
            MLog.d("api", "request body " + getParamContent(originalRequestBody));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return request.newBuilder().method(request.method(), originalRequestBody).build();
    }

    /**
     * 获取常规post请求参数
     */
    private String getParamContent(RequestBody body) throws IOException {
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        return buffer.readUtf8();
    }

    /**
     * 对get请求做统一参数处理
     */
    private Request rebuildGetRequest(Request request) {
        if (commonParams == null || commonParams.size() == 0) {
            return request;
        }
        String url = request.url().toString();
        int separatorIndex = url.lastIndexOf("?");
        StringBuilder sb = new StringBuilder(url);
        if (separatorIndex == -1) {
            sb.append("?");
        }
        for (String commonParamKey : commonParams.keySet()) {
            sb.append("&").append(commonParamKey).append("=").append(commonParams.get(commonParamKey));
        }
        Request.Builder requestBuilder = request.newBuilder();
        return requestBuilder.url(sb.toString()).build();
    }
}
